type TreeNode = {
    id: number
    name: string
    parentId: number
    status: string
    children?: TreeNode[]
    label?: string
    disabled?: boolean
}

export function useTree(arr: TreeNode[]) {
    // 处理机构树
    const arrayToTree = (items: TreeNode[], parentIdKey = 'parentId', idKey = 'id') => {
        const tree: TreeNode[] = []
        const childrenOf: Record<number, TreeNode[]> = {}
        items.forEach((item) => {
            // 设置 label 属性
            item.label = item.name
            const parentId = item[parentIdKey]
            if (parentId === 0) {
                tree.push(item)
            }
            else {
                if (!childrenOf[parentId]) {
                    childrenOf[parentId] = []
                }
                childrenOf[parentId].push(item)
            }
        })
        function findChildren(items: TreeNode[]): TreeNode[] {
            return items.map((item) => {
                const foundChildren = childrenOf[item[idKey]] || []
                item.children = findChildren(foundChildren)
                item.disabled = item.status === '1'
                // item.hasChildren = item.children.length
                return item
            })
        }
        return findChildren(tree)
    }

    const treeData = arrayToTree(arr, 'parentId', 'id')
    console.log('treeData', treeData)

    return {
        arrayToTree,
        treeData,
    }
}
